02. Big Picture and Intuition

Big Picture and Intuition

ND079 JPND C2 L04 A02 Big Picture And Intuition V3

What is Reflection?

Reflection, which is sometimes called introspection, is the ability of a program to examine its own structure at runtime.

Java has a very powerful reflection system that allows the program to see which classes it has loaded, what methods each class declares, what annotations are present, and much more. Java is somewhat special in this regard, because not all languages offer reflection.

Static vs Dynamic Code

Static Code

Normally, when you write a program, all the class names, method names, and variable names are known statically, when the code is being written and compiled:

Foo myObject = new Foo();

Static code gives you the benefit of static analysis, which includes compile-type checking of static symbols like class and method names, and useful IDE features like auto-completion.

The Java compiler will return an error if you used an invalid class or method name.

Dynamic Code

You can also create a Foo object without static symbol names. This is sometimes called dynamic coding:

Object myObject = Class.forName("Foo").getConstructor().newInstance();

Writing this kind of code, you won't get any static or compile-time checks to make sure you got the class name correct. If you run this code and there is no class named "Foo", a ClassNotFoundException will be thrown.

What are some disadvantages of using dynamic code?

SOLUTION:
  • Can be slower than static code.
  • Can lead to fragile programs.